<template>
  <MyModal ref="myModal" title="修改" :top="40" :width="600">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="loginForm" :model="formState" style="width: 500px">
          <a-form-item has-feedback name="answerText">
            <a-textarea
              ref="textareaRef"
              :rows="10"
              v-model:value="formState.answerText"
              placeholder="回复内容"
              autocomplete="off"
              style="max-height: 456px"
              @click="getPosition"
            ></a-textarea>
          </a-form-item>

          <a @click="selectEmoji">
            <SmileOutlined style="font-size: 26px" />
          </a>

          <a-form-item>
            <div style="width: 500px">
              <a-tag
                style="margin: 5px; color: rgba(0, 0, 0, 0.65); cursor: pointer"
                v-for="(item, index) in tagList"
                :key="index"
                @click="copyTag(item)"
              >
                {{ item }}
              </a-tag>
            </div>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-button style="margin-right: 10px; border-radius: 6px" @click="myModal.cancelModal()">
              取消
            </a-button>
            <a-button type="primary" style="border-radius: 6px" @click="handleSubmit">
              完成
            </a-button>
          </a-form-item>
        </a-form>

        <Emoji ref="emojiRef" @okEmoji="setOkEmoji"></Emoji>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import * as questionAnswerApi from '@/api/questionAnswer'
import { copyToCliboard } from '@/hooks/util.ts'
import { message } from 'ant-design-vue'
import Emoji from './Emoji.vue'

const myModal = ref()
const emojiRef = ref()
const textareaRef = ref(null)

const rowInfo = ref<any>()
const showModal = (record: any) => {
  rowInfo.value = record
  tagList.value = record.variables.split(',')
  formState.value.answerText = record.contentTemplate
  myModal.value?.showModal()
}

const tagList = ref([])

const emit = defineEmits<{
  refresh: [rowInfo: any]
}>()

defineExpose({
  showModal,
})

interface formState {
  answerText: string
}
const formState = ref<formState>({
  answerText: '',
})

// 复制文本
const copyTag = (text: string) => {
  copyToCliboard(`[${text}]`)
  // message.success('复制成功~')
}

const replaceEnglishSymbolsWithChinese = text => {
  // 定义英文符号到中文符号的映射
  const symbolMap = {
    '.': '。',
    ',': '，',
    '?': '？',
    '!': '！',
    ':': '：',
    ';': '；',
    '(': '（',
    ')': '）',
    // '[': '【',
    // ']': '】'
    '{': '｛',
    '}': '｝',
    '"': '“',
    "'": '’',
    '`': '‘',
    // '—': '——',
    // '-': '－',
    // '_': '＿',
    // '/': '／',
    '\\': '＼',
    // '|': '｜',
    // '@': '＠',
    // '#': '＃',
    // '$': '＄',
    // '%': '％',
    // '^': '＾',
    // '&': '＆',
    // '*': '＊',
    // '=': '＝',
    // '+': '＋',
    // '<': '＜',
    // '>': '＞'

    /* 注意：这里没有包括 '~'，因为 '~' 在中文中通常不作为标点符号使用
        如果需要替换，可以添加：'~': '～' */
  }
  return text.replace(/[.,!?;:(){}\[\]"`—_\/\\|@#$%^&*=+<>]/g, function (match) {
    return symbolMap[match] || match // 如果找不到对应的中文符号，则返回原符号
  })
}

const handleSubmit = () => {
  let originalText = replaceEnglishSymbolsWithChinese(formState.value.answerText)
  console.log(originalText)

  rowInfo.value!.content = originalText
  // console.log('rowInfo=', rowInfo.value)

  emit('refresh', rowInfo.value)
  myModal.value?.cancelModal()
}
// 获取文本域的光标位置
let cursorPosition = ref<number>(0)
const getPosition = () => {
  if (textareaRef.value) {
    const textareaElement = textareaRef.value.$el.querySelector('textarea') // 获取原生的 textarea 元素
    const selectionStart = textareaElement.selectionStart
    const selectionEnd = textareaElement.selectionEnd
    console.log('光标位置:', { selectionStart, selectionEnd })
    cursorPosition.value = selectionStart as number
  }
}

// 选择表情
const selectEmoji = () => {
  emojiRef.value.showModal()
}

// 已经选好表情
const setOkEmoji = (args: string) => {
  if (!formState.value.answerText) {
    formState.value.answerText = args
  } else {
    let substringAfterPosition = formState.value.answerText.slice(cursorPosition.value)
    console.log(substringAfterPosition, 'substringAfterPosition')

    let result =
      formState.value.answerText.slice(0, cursorPosition.value) + args + substringAfterPosition
    console.log(result, 'result')

    formState.value.answerText = result
  }
}
</script>
